package com.ybb.controller;

import com.ybb.account.service.UserAccountService;
import com.ybb.common.configuration.BusinessException;
import com.ybb.common.configuration.response.RetResponse;
import com.ybb.common.configuration.response.RetResult;
import com.ybb.order.service.OrderService;
import com.ybb.order.vo.OrderVo;
import com.ybb.stock.service.GoodsStockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private UserAccountService userAccountService;

    @Autowired
    private GoodsStockService stockService;

    /**
     * 创建订单，锁定库存
     */
    @PostMapping("/api/order/create")
    @Transactional
    public RetResult createOrder(OrderVo orderVo) throws BusinessException {
        //锁库存并判断是否够
        Integer num = stockService.getGoodsStockWithLock(orderVo.getSku(), orderVo.getMerchant());
        if (num < orderVo.getNum()) {
            throw new BusinessException("库存不足");
        }
        //创建订单(未支付）
        Integer orderId = orderService.createOrderNopay(orderVo);

        return RetResponse.makeOKRsp("创建成功订单"+orderId);
    }

    /**
     * 订单支付
     */
    @PostMapping("/api/order/{orderId}/pay")
    @Transactional
    public RetResult payOrder(@RequestParam("orderId") Integer orderId) throws BusinessException {
        OrderVo orderVo = orderService.getOrder(orderId);
        //获取并锁住用户的金额表，防止超额使用。
        Double balance = userAccountService.getUserAccountBalanceInLock(orderVo.getUser());
        //判断余额是否够
        Double amount = orderVo.getPrice() * orderVo.getNum();
        if (amount > balance) {
            //无需回库，因为后面有可能充上钱后再支付。
            throw new BusinessException("用户余额不足");
        }
        //确认订单
        orderService.confirmPayOrder(orderId);
        return RetResponse.makeOKRsp("支付成功");
    }
}
